//
//  SLVIPJoinViewController.m
//  StarLight
//
//  Created by Duke.wu on 16/6/6.
//  Copyright © 2016年 Duke.Wu. All rights reserved.
//

#import "SLVIPJoinViewController.h"
#import "SLVIPMonthButton.h"
#import "SLLevelStarView.h"
#import "DateTools.h"
#import "NSDate+Utils.h"
#import "SLMonthView.h"
#import "BKJH5ViewController.h"
#import "SLVIPViewModel.h"
#import "BKJPayWaysTableViewCell.h"
#import "STPopup.h"
#import "SLStarLevelViewController.h"
#import "SLButton.h"
#import "SLMineViewModel.h"



#define kUrlcd @"http://xinmatou.net/share/cdintroduce.html"
#define kUrlhz @"http://xinmatou.net/share/hzintroduce.html"

@interface SLVIPJoinViewController ()<UITableViewDataSource,UITableViewDelegate>{
  UIView *_backView;
}

@property (nonatomic, strong)SLVIPViewModel *vipVM;

@property (nonatomic, strong)UIView *joinView;
/**会员缴费*/
@property (nonatomic, strong)UIButton *joinBtn;
/**底部 Line*/
@property (nonatomic, strong)UIView *bottomLine;
/**VIP 说明*/
@property (nonatomic, strong)UIButton *aboutBtn;
/**几星会员*/
@property (nonatomic, strong)SLButton *starMemberBtn;
/**会员截止日期*/
@property (nonatomic, strong)UILabel *finalTimeLB;
/**钻个数*/
@property (nonatomic, strong)SLLevelStarView *levelStarView;
/**支付*/
@property (nonatomic, strong)UIButton *payBtn;
/**头像*/
@property (nonatomic, strong)UIImageView *membIcon;
/**月份*/
@property (nonatomic, strong)SLMonthView *monthView;

@property (nonatomic, strong)BKJH5ViewController *h5VC;

@property (nonatomic, strong)UITableView *payWaysTableView;

@property (nonatomic, strong)SLVIPPriceModel *seletPriceModel;

@property (nonatomic, strong)SLMineViewModel *mineVM;


@end



@implementation SLVIPJoinViewController

/**
 *  支付方式
 */
static NSString *payWay;
/**
 *  会员等级
 */
static NSInteger starLevel = 1;
/**
 *  会员时间
 */
static NSInteger starMonth = 0;



- (void)viewDidLoad {
    [super viewDidLoad];
  [self.vipVM getVIPPrice];
  [self addUI];
  [self addConstrains];
  [self addObservers];
  
  if (self.mineVM.indexModel.role >0) {
    [self congfigJoinViewWithLevel:@(self.mineVM.indexModel.role)];
    [self.levelStarView setLevelStarWithLevel:self.mineVM.indexModel.role+1];
    self.finalTimeLB.text = self.mineVM.indexModel.time;
  }
    // Do any additional setup after loading the view.
}

- (void)viewWillAppear:(BOOL)animated{
  [super viewWillAppear:animated];
  self.view.backgroundColor = SLBlackColor;
  self.title = @"VIP办理";
  [self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
  [self.navigationController.navigationBar setShadowImage:[UIImage new]];
  [self.navigationController setNavigationBarHidden:NO animated:YES];
}

- (void)viewWillDisappear:(BOOL)animated{
  [super viewWillDisappear:animated];
  [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
  [self.navigationController.navigationBar setShadowImage:nil];
  [self.navigationController setNavigationBarHidden:YES animated:YES];
}


- (void)addObservers{
  @weakify(self)
  
  // 更新month View
  [[RACObserve(self.vipVM, start1Arr) filter:^BOOL(NSMutableArray *priceArr) {
    return priceArr.count > 0;
  }] subscribeNext:^(NSMutableArray *priceArr) {
    @strongify(self)
    [self configMonthWithPriceArr:priceArr];
  }];
  
  [RACObserve(self.mineVM, indexModel) subscribeNext:^(id x) {
    @strongify(self)
    if (self.mineVM.indexModel.role >0) {
      [self congfigJoinViewWithLevel:@(self.mineVM.indexModel.role)];
      [self.levelStarView setLevelStarWithLevel:self.mineVM.indexModel.role+1];
      self.finalTimeLB.text = self.mineVM.indexModel.time;
    }
  }];
  
  [self.monthView returnMonthAndPrice:^(SLVIPPriceModel *model) {
    @strongify(self)
    NSDate *date = [NSDate date];
    NSDate *newDate = [date dateByAddingMonths:model.month];
    NSString *datestr = [newDate stringYearMonthDay];
    self.finalTimeLB.text = [NSString stringWithFormat:@"会员截止日期 :%@",datestr];
    self.seletPriceModel = model;
    starMonth = model.month;
  }];

  
}


- (void)configMonthWithPriceArr:(NSMutableArray *)priceArr{
  [self.monthView configMonthView:priceArr];
}


- (void)showLevelChoese{
  SLStarLevelViewController *levelChoeseVC = [[SLStarLevelViewController alloc] init];
  STPopupController *popvc = [[STPopupController alloc] initWithRootViewController:levelChoeseVC];
  [popvc presentInViewController:self];
  
  
  @weakify(self)
  [levelChoeseVC returnReturnStarLevel:^(NSNumber *level) {
    @strongify(self)
    [self congfigJoinViewWithLevel:level];
  }];
}




- (void)congfigJoinViewWithLevel:(NSNumber *)level{
  starLevel = level.integerValue;
  
  [self.levelStarView setLevelStarWithLevel:level.integerValue +1];
  if (level.integerValue == 0) {
    [self.monthView configMonthView:self.vipVM.start1Arr];
    self.starMemberBtn.lefttitleLB.text = @"一星会员" ;
  }else if (level.integerValue == 1){
    [self.monthView configMonthView:self.vipVM.start2Arr];
    self.starMemberBtn.lefttitleLB.text = @"二星会员";
  }else if (level.integerValue == 2){
    [self.monthView configMonthView:self.vipVM.start3Arr];
    self.starMemberBtn.lefttitleLB.text = @"三星会员";
  }else if (level.integerValue == 3){
    [self.monthView configMonthView:self.vipVM.start4Arr];
    self.starMemberBtn.lefttitleLB.text = @"四星会员";
  }else if (level.integerValue == 4){
    [self.monthView configMonthView:self.vipVM.start5Arr];
    self.starMemberBtn.lefttitleLB.text = @"五星会员";
  }
  
  
  
}

#pragma mark - Private methods

- (void)showVIPJoin{
  self.joinBtn.selected = YES;
  self.aboutBtn.selected = NO;
  [self.joinView mas_updateConstraints:^(MASConstraintMaker *make) {
    make.left.equalTo(self.view);
  }];
  
  [self.bottomLine mas_remakeConstraints:^(MASConstraintMaker *make) {
    make.centerX.equalTo(self.joinBtn);
    make.width.equalTo(self.joinBtn);
    make.bottom.equalTo(self.joinView.mas_top);
    make.height.equalTo(@4);
  }];
  
  [self.h5VC.view mas_updateConstraints:^(MASConstraintMaker *make) {
    make.left.equalTo(self.view).offset(SCREEN_WIDTH);
  }];
  
  [self.view layoutIfNeeded];
}

- (void)showVIPAbout{
  self.joinBtn.selected = NO;
  self.aboutBtn.selected = YES;
  [self.joinView mas_updateConstraints:^(MASConstraintMaker *make) {
    make.left.equalTo(self.view).offset(-SCREEN_WIDTH);
  }];
  
  [self.bottomLine mas_remakeConstraints:^(MASConstraintMaker *make) {
    make.centerX.equalTo(self.aboutBtn);
    make.width.equalTo(self.joinBtn);
    make.bottom.equalTo(self.joinView.mas_top);
    make.height.equalTo(@4);
  }];
  
  [self.h5VC.view mas_updateConstraints:^(MASConstraintMaker *make) {
    make.left.equalTo(self.view);
  }];
  [self.view layoutIfNeeded];
}


- (void)toPay{
  
  @weakify(self)
  if ([self isCanPay]) {
    [self.vipVM payWithStar:starLevel channel:payWay time:starMonth block:^(NSDictionary *charge) {
      @strongify(self)
      [SVProgressHUD dismiss];
      [Pingpp createPayment:charge viewController:self appURLScheme:@"com.starLight.iosApp" withCompletion:^(NSString *result, PingppError *error) {
        
        if ([result isEqualToString:@"success"]) {
          // 支付成功
          [[NSNotificationCenter defaultCenter] postNotificationName:kJoinVipSucess object:nil];
          [self.navigationController popViewControllerAnimated:YES];
        } else {
          // 支付失败或取消
          [SVProgressHUD showErrorWithStatus:@"支付失败"];
        }
        
      }];

    }];
  }else{
    [SVProgressHUD showImage:nil status:@"请完善支付信息"];
  }
}




-(BOOL)isCanPay{
  return self.seletPriceModel != nil && payWay != nil && starMonth  != 0;
}





#pragma mark - UITableViewDataSource,UITableViewDelegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
  
  return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
  
  return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
  return 1.f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
  return 1.f;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
  UIView *view=[[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 1)];
  view.backgroundColor = [UIColor defeutBackgroudColor];
  return view;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  if (indexPath.section == 0) {
    BKJPayWaysTableViewCell *cell = [[BKJPayWaysTableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"section1"];
    cell.label.text = @"支付宝支付";
    cell.imgView.image = [UIImage imageNamed:@"Alipay to pay"];
    return cell;
  }else{
    BKJPayWaysTableViewCell *cell = [[BKJPayWaysTableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"section2"];
    cell.label.text = @"微信支付";
    cell.imgView.image = [UIImage imageNamed:@"WeChat payment"];
    return cell;
  }
  
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
  return 40*MIX_H;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
  if (indexPath.section == 0) {
    // 支付宝
    payWay = @"1";
  }else if(indexPath.section == 1){
    // 微信
    payWay = @"2";
  }
  BKJPayWaysTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
  cell.selected = YES;
}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
  BKJPayWaysTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
  cell.selected = NO;
}


#pragma mark - UI



- (void)addUI{
  _backView = [UIView new];
  _backView.backgroundColor = [UIColor whiteColor];

  [self.view addSubview:self.joinView];
  [self.view addSubview:self.aboutBtn];
  [self.view addSubview:self.joinBtn];
  [self.view addSubview:self.bottomLine];
  [self.view addSubview:self.h5VC.view];
  [self.joinView addSubview:_backView];
  [self.joinView addSubview:self.levelStarView];
  [self.joinView addSubview:self.starMemberBtn];
  [self.joinView addSubview:self.finalTimeLB];
  [self.joinView addSubview:self.membIcon];
  [self.joinView addSubview:self.monthView];
  [self.joinView addSubview:self.payWaysTableView];
  [self.joinView addSubview:self.payBtn];
  
}

- (void)addConstrains{
  [self.joinBtn mas_makeConstraints:^(MASConstraintMaker *make) {
    make.top.equalTo(self.mas_topLayoutGuideBottom).offset(17);
    make.right.equalTo(self.view.mas_centerX).offset(-50);
    make.size.mas_equalTo(CGSizeMake(70, 30));
  }];
  
  [self.aboutBtn mas_makeConstraints:^(MASConstraintMaker *make) {
    make.top.equalTo(self.mas_topLayoutGuideBottom).offset(17);
    make.left.equalTo(self.view.mas_centerX).offset(50);
    make.size.mas_equalTo(CGSizeMake(70, 30));
  }];
  
  [self.joinView mas_makeConstraints:^(MASConstraintMaker *make) {
    make.top.equalTo(self.joinBtn.mas_bottom).offset(20);
    make.left.equalTo(self.view);
    make.width.equalTo(self.view);
    make.bottom.equalTo(self.view);
  }];
  
  
  
  [_backView mas_makeConstraints:^(MASConstraintMaker *make) {
    make.left.width.centerX.equalTo(self.joinView);
    make.top.equalTo(self.joinView);
    make.bottom.equalTo(self.monthView.mas_top);
  }];

  
  
  [self.bottomLine mas_makeConstraints:^(MASConstraintMaker *make) {
    make.centerX.equalTo(self.joinBtn);
    make.width.equalTo(self.joinBtn);
    make.bottom.equalTo(self.joinView.mas_top);
    make.height.equalTo(@4);
  }];
  
  [self.starMemberBtn mas_makeConstraints:^(MASConstraintMaker *make) {
    make.left.top.equalTo(self.joinView).offset(20);
    make.size.mas_equalTo(CGSizeMake(105, 30));
  }];
  
  [self.membIcon mas_makeConstraints:^(MASConstraintMaker *make) {
    make.right.equalTo(self.joinView).offset(-20);
    make.top.equalTo(self.joinView).offset(20);
    make.size.mas_equalTo(CGSizeMake(40, 40));
  }];
  
  [self.levelStarView mas_makeConstraints:^(MASConstraintMaker *make) {
    make.centerY.equalTo(self.membIcon);
    make.right.equalTo(self.membIcon.mas_left).offset(-20);
    make.size.mas_equalTo(CGSizeMake(78, 11));
  }];
  
  [self.finalTimeLB mas_makeConstraints:^(MASConstraintMaker *make) {
    make.top.equalTo(self.starMemberBtn.mas_bottom).offset(20);
    make.left.equalTo(self.starMemberBtn);
  }];
  
  [self.monthView mas_makeConstraints:^(MASConstraintMaker *make) {
    make.left.width.centerX.equalTo(self.joinView);
    make.top.equalTo(self.finalTimeLB.mas_bottom).offset(20);
    make.height.equalTo(@(200*MIX_W));
  }];
  
  
  [self.payWaysTableView mas_makeConstraints:^(MASConstraintMaker *make) {
    make.left.width.centerX.equalTo(self.joinView);
    make.bottom.equalTo(self.payBtn.mas_top);
    make.height.equalTo(@(100*MIX_W));
  }];
  
  [self.h5VC.view mas_makeConstraints:^(MASConstraintMaker *make) {
    make.top.equalTo(self.joinBtn.mas_bottom).offset(20);
    make.left.equalTo(self.view).offset(SCREEN_WIDTH);
    make.width.equalTo(self.view);
    make.bottom.equalTo(self.view);
  }];
  
  
  [self.payBtn mas_makeConstraints:^(MASConstraintMaker *make) {
    make.left.width.centerX.equalTo(self.joinView);
    make.bottom.equalTo(self.joinView);
    make.height.equalTo(@50);
  }];
  
  
}





#pragma mark - getter



- (UIView *)joinView{
  if (!_joinView) {
    _joinView = [UIView new];
    _joinView.backgroundColor = [UIColor defeutBackgroudColor];
  }
  return _joinView;
}

- (UIView *)bottomLine{
  if (!_bottomLine) {
    _bottomLine = [[UIView alloc] init];
    _bottomLine.backgroundColor = SLYellowColor;
  }
  return _bottomLine;
}

- (UIImageView *)membIcon{
  if (!_membIcon) {
    _membIcon = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"head"]];
    [_membIcon sd_setImageWithURL:[NSURL URLWithString:self.memberImage] placeholderImage:IMG(@"head") options:SDWebImageRetryFailed | SDWebImageLowPriority];
  }
  return _membIcon;
}

- (UILabel *)finalTimeLB{
  if (!_finalTimeLB) {
    NSString *date = [NSDate stringYearMonthDayWithDate:nil];
    _finalTimeLB = [UILabel labelWithFontSize:10 textColor:[UIColor grayColor] text:[NSString stringWithFormat:@"会员截止日期:%@",date]];
  }
  return _finalTimeLB;
}

- (SLLevelStarView *)levelStarView{
  if (!_levelStarView) {
    _levelStarView = [[SLLevelStarView alloc] init];
  }
  return _levelStarView;
}

- (UIButton *)joinBtn{
  if (!_joinBtn) {
    _joinBtn = [UIButton buttonWithTitle:@"VIP缴费"];
    _joinBtn.selected = YES;
    _joinBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [_joinBtn addTarget:self action:@selector(showVIPJoin) forControlEvents:UIControlEventTouchUpInside];
    [_joinBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    [_joinBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
  }
  return _joinBtn;
}

- (UIButton *)aboutBtn{
  if (!_aboutBtn) {
    _aboutBtn = [UIButton buttonWithTitle:@"VIP说明"];
    _aboutBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [_aboutBtn addTarget:self action:@selector(showVIPAbout) forControlEvents:UIControlEventTouchUpInside];
    [_aboutBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    [_aboutBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
  }
  return _aboutBtn;
}

- (UIButton *)payBtn{
  if (!_payBtn) {
    _payBtn = [UIButton buttonWithTitle:@"支付"];
    _payBtn.backgroundColor = SLYellowColor;
    [_payBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    _payBtn.titleLabel.font = [UIFont systemFontOfSize:18];
    [_payBtn addTarget:self action:@selector(toPay) forControlEvents:UIControlEventTouchUpInside];
  }
  return _payBtn;
}

- (SLButton *)starMemberBtn{
  if (!_starMemberBtn) {
    _starMemberBtn = [[SLButton alloc] init];
    _starMemberBtn.lefttitleLB.font = [UIFont boldSystemFontOfSize:15];
    _starMemberBtn.lefttitleLB.text = @"一星会员";
    _starMemberBtn.rightImage.image = [UIImage imageNamed:@"v"];
//    [_starMemberBtn setTitle:@"一星会员" forState: UIControlStateNormal];
//    [_starMemberBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//    [_starMemberBtn setImage:[UIImage imageNamed:@"v"] forState:UIControlStateNormal];
//    [_starMemberBtn dw_titleImageHorizontalAlignmentWithSpace:15];
//    [_starMemberBtn dw_imageTitleHorizontalAlignmentWithSpace:15];
    [_starMemberBtn addTarget:self action:@selector(showLevelChoese) forControlEvents:UIControlEventTouchUpInside];
  }
  return _starMemberBtn;
}

- (SLMonthView *)monthView{
  if (!_monthView) {
    _monthView = [[SLMonthView alloc] init];
  }
  return _monthView;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (SLVIPViewModel *)vipVM{
  if (!_vipVM) {
    _vipVM = [SLVIPViewModel new];
  }
  return _vipVM;
}

- (UITableView *)payWaysTableView{
  if (!_payWaysTableView) {
    _payWaysTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    [_payWaysTableView registerClass:[BKJPayWaysTableViewCell class] forCellReuseIdentifier:@"cell"];
    _payWaysTableView.delegate = self;
    _payWaysTableView.dataSource = self;
  }
  return _payWaysTableView;
}


- (BKJH5ViewController *)h5VC{
  if (!_h5VC) {
    _h5VC = [BKJH5ViewController new];
    _h5VC.h5Url = self.userType == 1 ? kUrlhz : kUrlcd;
  }
  return _h5VC;
}

- (SLMineViewModel *)mineVM{
  _mineVM = [SLMineViewModel shareInstance];
  return _mineVM;
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
